<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of LoginController
 *
 * @author Admin
 */
class User_LoginController extends Zend_Controller_Action {

    public function init() {
        $this->_sessionNamespace = new Zend_Session_Namespace('User_login');
        $this->flashMessenger = $this->_helper->FlashMessenger;
    }

    public function preDispatch() {
       $this->_helper->layout->disableLayout();
       $view = new Zend_View();
       $view->headTitle(' > Login');
       $view->headLink()->appendStylesheet($view->baseURI() .'css/style.css');
       $view->headScript()->appendFile($view->baseURI() .'js/jquery.js');
    }

    public function indexAction() {

        $userModel = new Application_Model_UserModel();
        //create form
        $form = new Application_Form_users_LoginForm();

        // if request is post
        if ($this->_request->isPost()) {

            // if form is valid
            if ($form->isValid($_POST)) {

                $adapter = $userModel->_getAuthAdapter();
                $adapter->setIdentity($form->getValue('email'));
                $adapter->setCredential($form->getValue('password'));

                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($adapter);
                if ($result->isValid()) {
                    $user = $adapter->getResultRowObject();
                    $auth->getStorage()->write($user);
                    if($user->role=='user')
                    {
                        switch($user->department)
                        {
                            case 'marketing':{
                                $this->_redirect("marketing/mynotification");
                                break;
                            }
                        }
                    }
                    $this->_redirect("home/dashboard");
                    exit;
                }
                $this->flashMessenger->addMessage('failure');
                $this->flashMessenger->addMessage('Email /password not valid');
                $this->_redirect("user/login");
                exit;
            }
        }

        // assign form variable to view
        $this->view->form = $form;
    }
    
    public function logoutAction(){
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect("user/login");
    }
}